#include "mutexbase.h"
#include "cmsis_os.h"

MutexBase::MutexBase(bool recursive)
{
    CreateMutex(recursive);
}

MutexBase::~MutexBase()
{
    osMutexDelete(m_mutexHandle);
}

bool MutexBase::TryLock()
{
    return Lock(0);
}

bool MutexBase::Lock(int timeout)
{
    if(timeout == -1)
    {
        timeout = osWaitForever;
    }
    
    return osMutexAcquire(m_mutexHandle, timeout) == osOK;
}

void MutexBase::UnLock()
{
    osMutexRelease(m_mutexHandle);
}

void MutexBase::CreateMutex(bool recursive)
{
    osMutexAttr_t attr = {0};

    attr.name = "mutex";
    if(recursive)
    {
        attr.attr_bits = osMutexRecursive;
    }
    m_mutexHandle = osMutexNew(&attr);
}
